/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jsysacc.asistencia.view.resources.commons;

import java.awt.Window;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Carlos
 */
public class JTextFieldToUpperCase extends PlainDocument {

    int numChars = 0;
    boolean soloNumeros = false;

    public JTextFieldToUpperCase() {
        numChars = 50;
    }

    public JTextFieldToUpperCase(int numChars, boolean soloNumeros) {
        this.numChars = numChars;
        this.soloNumeros = soloNumeros;
    }

    @Override
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        boolean valid = true;
        char[] insertChars = str.toCharArray();

        if (insertChars.length + getLength() <= this.numChars) {
            if (soloNumeros) {
                for (int i = 0; i < insertChars.length; i++) {
                    if (!Character.isDigit(insertChars[i])) {
                        valid = false;
                        break;
                    }
                }
            }
        } else {
            valid = false;
        }

        if (valid) {
            super.insertString(offset, str.toUpperCase(), attr);
        } else {
            Window w = new Window(null);
            w.getToolkit().beep();
        }
    }

}
